package com.hll.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 使用AES加密与解密																																																																																																																																																																																																																																																															
 * @author yandx
 */
public class AESUtils {
	private static final String ALGORITHM = "AES";

	private static final int KEY_SIZE = 128;


    private static final String KEY1 = "UITN25LMUQC436IM";

	public final static String ENCODING = "UTF-8";

	/**
	 * <p>加密 </p>
	 * @param data 需要加密内容
	 * @param key 密钥
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(String data, String key) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
			kgen.init(KEY_SIZE, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, ALGORITHM);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
			byte[] byteContent = data.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**解密
	 * @param content  待解密内容
	 * @param key 解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String key) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
			kgen.init(KEY_SIZE, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, ALGORITHM);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, keySpec);// 初始化
			byte[] result = cipher.doFinal(content);
            System.out.println(result+"!@!@!@!@");
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**将二进制转换成16进制
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**将16进制转换为二进制
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length()/2];
		for (int i = 0;i< hexStr.length()/2; i++) {
			int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
			int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

    /**
     * 解码AES
     * @param encryptResultStr
     * @return
     */
    public static String decode(String encryptResultStr){

        String password = KEY1;

        BASE64Decoder base64Decoder=new BASE64Decoder();
        byte[] decryptFrom = new byte[0];
        try {

            System.out.println("#########");
            decryptFrom = base64Decoder.decodeBuffer(encryptResultStr);
            System.out.println("%^&%^&%^&%^&"+decryptFrom);
        } catch (IOException e) {

            System.out.println("@@@@@@@@@@@@@#");
            e.printStackTrace();
        }
        byte[] decryptResult = decrypt(decryptFrom,password);
        System.out.println("解密后：" + decryptResult+"234234234");

        String decodeResult = new String(decryptResult);

        System.out.println("解密后：" + decodeResult);


        return   new String(decodeResult);
    }


    public static String encode(String content){

        String password = KEY1;
        //加密
        System.out.println("加密前：" + content);
        byte[] encryptResult = encrypt(content, password);

        BASE64Encoder base64Encoder =new BASE64Encoder();
        String encryptResultStr = base64Encoder.encode(encryptResult);
//		String encryptResultStr = parseByte2HexStr(encryptResult);
        System.out.println("加密后：" + encryptResultStr);

        return  encryptResultStr;
    }


	public static void main(String[] args) {
		String content = "example";
		String password = "UITN25LMUQC436IM";
		//加密
		System.out.println("加密前：" + content);
		byte[] encryptResult = encrypt(content, password);

		BASE64Encoder base64Encoder =new BASE64Encoder();
		String encryptResultStr = base64Encoder.encode(encryptResult);
//		String encryptResultStr = parseByte2HexStr(encryptResult);
		System.out.println("加密后：" + encryptResultStr);
		//解密
		BASE64Decoder base64Decoder=new BASE64Decoder();
		byte[] decryptFrom = new byte[0];
		try {
			decryptFrom = base64Decoder.decodeBuffer(encryptResultStr);
		} catch (IOException e) {
			e.printStackTrace();
		}

		byte[] decryptResult = decrypt(decryptFrom,password);

		System.out.println("解密后：" + new String(decryptResult));
        decode(encryptResultStr);
	}
}																																																																																																																																																																																																																																																															
